package com.linwen.excise.leetcode;

import java.util.Stack;

/**
 * @author : linwen
 * @date : 下午10:58 2020/11/29
 */
public class _20有效的括号 {
    public static void main(String[] args) {
        String str = "(([]){})";
        System.out.println(isValid(str));
        System.out.println(isValid2(str));
        System.out.println(isValid3(str));
    }

    private static boolean isValid(String s) {
        if(s.length()%2!=0){
            return false;
        }
        Stack<Character> stack = new Stack<Character>();
        for (int i=0;i<s.length();i++){
            if(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{'){
                stack.push(s.charAt(i));
            }else if(s.charAt(i)==')'){
                if(stack.isEmpty()||'('!=stack.pop()){
                    return false;
                }
            }else if(s.charAt(i)==']'){
                if(stack.isEmpty()||'['!=stack.pop()){
                    return false;
                }
            }else if(s.charAt(i)=='}'){
                if(stack.isEmpty()||'{'!=stack.pop()){
                    return false;
                }
            }
        }
        if(stack.isEmpty()){
            return true;
        }else{
            return false;
        }
    }

    private static boolean isValid2(String s) {
        int loop = s.length();
        if(loop%2 != 0){
            return false;
        }
        while(s.indexOf("{}")!=-1||s.indexOf("()")!=-1
                ||s.indexOf("[]")!=-1||s.length()==0){
            if(s.length()==0){
                return true;
            }
            s = s.replace("()","");
            s = s.replace("{}","");
            s = s.replace("[]","");
        }
        return false;
    }

    private static boolean isValid3(String s) {
        int loop = s.length();
        if(loop%2!=0){
            return false;
        }
        Stack<Character> stack = new Stack<>();
        char[] chars = s.toCharArray();
        for (int i = 0; i < loop; i++) {
            if('('==chars[i]){stack.push(')');}
            else if('['==chars[i]){stack.push(']');}
            else if('{'==chars[i]){stack.push('}');}
            else if (stack.isEmpty()||chars[i]!=stack.pop()){return false;}
        }
        if(stack.isEmpty()){
            return true;
        }
        return false;
    }
}
